package com.hs.handler;

import com.alibaba.fastjson.JSON;
import com.hs.enums.AppHttpCodeEnum;
import com.hs.utils.ResultResponse;
import com.hs.utils.WebUtil;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
// 认证过程中出现异常
public class AuthenticationEntryPointImpl implements AuthenticationEntryPoint {

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) {
        authException.printStackTrace();
        ResultResponse<?> result = null;

        if (authException instanceof BadCredentialsException) {
            result = ResultResponse.fail(AppHttpCodeEnum.LOGIN_ERROR.getCode(),authException.getMessage());
        } else if (authException instanceof InsufficientAuthenticationException) {
            result = ResultResponse.fail(AppHttpCodeEnum.NEED_LOGIN.getCode(),AppHttpCodeEnum.NEED_LOGIN.getMsg());
        }else {
            result = ResultResponse.fail(AppHttpCodeEnum.SYSTEM_ERROR.getCode(),"认证或授权出现问题");
        }

        String json = JSON.toJSONString(result);
        //处理异常
        WebUtil.renderString(response,json);
    }
}
